package com.lh.recallbootrabbitmq.manage;

import com.lh.recallbootrabbitmq.bean.MqExchange;
import com.lh.recallbootrabbitmq.constants.ExchangeTypeEnum;
import com.lh.recallbootrabbitmq.exception.RabbitMQException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @author lh
 * @Description: 交换机管理类
 * @date 2021/8/17 16:30
 */
@Component
public class ExchangeManage extends AbstractManage {
	private final static Logger logger = LoggerFactory.getLogger(ExchangeManage.class);
	@Autowired
	RabbitAdmin rabbitAdmin;

	/**
	 * 向rabbitMQ服务器注册指定的交换机以及交换机的类型
	 *
	 * @param mqExchange 交换机
	 * @return
	 */
	public Exchange declareExchange(MqExchange mqExchange) {
		logger.info("declare exchange is :" + mqExchange.toString());
		Exchange exchange = null;
		super.validate(mqExchange);
		exchange = this.initExchange(mqExchange);
		//声明交换机
		this.rabbitAdmin.declareExchange(exchange);
		logger.info("declare exchange success");
		return exchange;
	}

	/**
	 * 根据不同类型初始化不同类型的交换机
	 *
	 * @param mqExchange 交换机
	 * @return
	 */
	private Exchange initExchange(MqExchange mqExchange) {
		ExchangeTypeEnum exchangeTypeEnum = mqExchange.getType();
		switch (exchangeTypeEnum) {
			case DIRECT:
				return new DirectExchange(mqExchange.getName(), mqExchange.isDurable(), mqExchange.isAutoDelete(), mqExchange.getArguments());
			case TOPIC:
				return new TopicExchange(mqExchange.getName(), mqExchange.isDurable(), mqExchange.isAutoDelete(), mqExchange.getArguments());
			case FANOUT:
				return new FanoutExchange(mqExchange.getName(), mqExchange.isDurable(), mqExchange.isAutoDelete(), mqExchange.getArguments());
			case HEADERS:
				return new HeadersExchange(mqExchange.getName(), mqExchange.isDurable(), mqExchange.isAutoDelete(), mqExchange.getArguments());
			default:
				return null;
		}
	}

	/**
	 * 从RabbitMQ服务端上删除指定的交换机
	 *
	 * @param exchangeName
	 * @return
	 */
	public boolean deleteExchange(String exchangeName) {
		logger.info("delete exchange is : " + exchangeName);

		if (StringUtils.isEmpty(exchangeName)) {
			throw new RabbitMQException("the parameter exchangeName couldn't not be null");
		}

		return this.rabbitAdmin.deleteExchange(exchangeName);
	}

	/**
	 * 废弃
	 *
	 * @param object
	 */
	@Override
	public void DefinedValidate(Object object) {

	}
}
